package org.btik.video.server.device.udp2;

import android.graphics.*;
import android.view.SurfaceHolder;
import androidx.annotation.NonNull;
import org.btik.video.server.VideoChannel;


/**
 * 安卓端不使用httpVideo
 *
 * @author lustre
 * @since 2022/10/30 11:36
 */
public class OneFrameVideoPainter implements VideoChannel, SurfaceHolder.Callback {
    private final Paint paint = new Paint();

    private SurfaceHolder surfaceHolder;
    Matrix matrix = new Matrix();


    @Override
    public void sendFrame(byte[] frame, int size) {
        if (surfaceHolder == null) {
            return;
        }
        Canvas canvas = surfaceHolder.lockHardwareCanvas();
        Bitmap bitmap = BitmapFactory.decodeByteArray(frame, 0, size);
        canvas.drawBitmap(bitmap, matrix, paint);
        surfaceHolder.unlockCanvasAndPost(canvas);
    }


    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        this.surfaceHolder = holder;
        // 计算缩放比
        Canvas canvas = holder.lockHardwareCanvas();
        int height = canvas.getHeight();
        int width = canvas.getWidth();
        holder.unlockCanvasAndPost(canvas);
        float sx = width / 480f;
        float sy = height / 320f;
        matrix.setScale(sx, sy);
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        this.surfaceHolder = null;
    }
}
